﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using UnityEngine;

public class SocketMgr : BaseMono
{
	public static SocketMgr Ins;
	private string addr = "127.0.0.1";
	private int port = 9000;

	//TCP套接字
	public BaseSocket Socket;

	private Packer packer;

	void Awake()
	{
		Ins = this;
	}

	void Start()
	{
		ConnectServer();
		packer.msgCenter.Regist(MethodDef.TestSend, new ChatHandler());
		packer.msgCenter.Regist(MethodDef.LoginCB, new ChatHandler());
		packer.msgCenter.Regist(MethodDef.Chat, new ChatHandler());
	}

	void Update()
	{
		packer.Excute();
	}

	public void ConnectServer()
	{
		Socket = new BaseSocket(addr, port);
		packer = new Packer(Socket);
		packer.OnRequest += () => MyLog.Log("Waiting");
		packer.OnCallback += data => MyLog.Log("Done : " + data.ReqResult);
		Socket.OnPack += packer.Pack;
		Socket.Connect();

	}

	public void Req(SendData data)
	{
		packer.Add(data);
	}

	private void OnDestroy()
	{
		Socket.CloseSocket();
	}
}
